package com.jhws.business.appconfig.service;

import com.jhws.business.appconfig.bo.AppConfigInfo;
import com.jhws.core.db.BaseDao;
import com.jhws.core.exception.BizException;
import com.jhws.util.GetId;
import com.jhws.util.LogHelper;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppConfigInfoService {
    @Resource
    private BaseDao BaseDao;

    /**
     * 保存配置
     *
     * @param appConfigInfo 配置信息
     */
    public void save(AppConfigInfo appConfigInfo) {
        List<AppConfigInfo> appConfigInfos = queryAppConfigInfoByWhere("where type='" + appConfigInfo.getType() + "'");
        if (appConfigInfos != null && appConfigInfos.size() > 0 && !appConfigInfos.get(0).getId().equals(appConfigInfo.getId())) {
            throw new BizException("类型已经存在！");
        }
        if (StringUtils.isEmpty(appConfigInfo.getId())) {
            appConfigInfo.setId(GetId.randomID());
        }
        appConfigInfo.setUpdateTime(new Date());
        BaseDao.merge(appConfigInfo);
    }

    /**
     * 查询配置信息
     *
     * @param deviceType 设备类型
     * @return 查询配置信息列表
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> queryAppConfigInfoPage(String deviceType) {
        String hql = "from AppConfigInfo where 1=1 ";
        if (StringUtils.isNotEmpty(deviceType)) {
            hql += " and device_type = '" + deviceType + "' ";
        }
        return BaseDao.queryPage(hql);
    }

    /**
     * 条件查询配置
     *
     * @param where 条件
     * @return
     */
    public List<AppConfigInfo> queryAppConfigInfoByWhere(String where) {
        return BaseDao.findList("from AppConfigInfo " + where);
    }

    /**
     * 删除配置信息
     *
     * @param appConfigInfo 配置信息
     */
    public void deleteAppConfigInfo(AppConfigInfo appConfigInfo) {
        BaseDao.delete(appConfigInfo);
    }

    /**
     * 条件删除配置信息
     *
     * @param where 条件
     */
    public void deleteAppConfigInfo(String where) throws Exception {
        String sql = "delete from app_config_info " + where;
        LogHelper.e("aaaaaa---->   " + sql);
        BaseDao.executeBySql(sql);
    }
}
